using System.Collections.Generic;
using System.Net.Sockets;

using GSN.Mail.Messages;

namespace GSN.Mail
{
    class POP3Client
    {
        private POP3Socket pop3Socket = new POP3Socket();

        public POP3Client()
        {
        }

        public void connect(string server, int port)
        {
            pop3Socket.Connect(server, port);
            string response = pop3Socket.readResponseLine();
            pop3Socket.verifyResponse(response); 
        }

        public void login(string username, string password)
        {
            if (!pop3Socket.Connected)
                throw new POP3Exception("POP3Client login: client not connected!");

            pop3Socket.writeCommand("USER {0}\r\n", username);
            pop3Socket.verifyResponse(pop3Socket.readResponseLine());
            pop3Socket.writeCommand("PASS {0}\r\n", password);
            pop3Socket.verifyResponse(pop3Socket.readResponseLine());
        }

        public void disconnect()
        {
            pop3Socket.writeCommand("QUIT\r\n");
            pop3Socket.readResponseLine(); // @@@ maybe not needed
            pop3Socket.Close();
        }

        public Message[] peek()
        {
            // send list command
            pop3Socket.writeCommand("LIST\r\n");
            string response = pop3Socket.readResponseLine();
            // check command ok
            pop3Socket.verifyResponse(response);
            // read list 
            List<int> msgList = new System.Collections.Generic.List<int>();
            while ((response = pop3Socket.readResponseLine()) != ".\r\n")
            {
                msgList.Add(int.Parse(response[0].ToString()));
            }

            List<Message> msgs = new List<Message>();

            string msg = null;
            // send retrieve commad
            foreach (int msgId in msgList)
            {
                msg = "";
                pop3Socket.writeCommand("RETR {0}\r\n", msgId);
                pop3Socket.verifyResponse(pop3Socket.readResponseLine());
                while ((response = pop3Socket.readResponseLine()) != ".\r\n")
                {
                    msg += response;
                }

                // parse message (bah..)
                msgs.Add(new Message(new Pop3MessageBuilder(msg)));
            }

            return msgs.ToArray();
        }
    }
}
